#!/bin/bash

echo "=== 快速修复和测试脚本 ==="
echo ""

# 1. 清理环境
echo "1. 清理环境..."
rm -f /tmp/ai_glass_*
pkill -f "ai_glass.*daemon" 2>/dev/null
sleep 1

# 2. 重新编译
echo "2. 重新编译..."
make clean && make

if [ $? -ne 0 ]; then
    echo "❌ 编译失败，请检查代码"
    exit 1
fi

echo "✅ 编译成功"
echo ""

# 3. 测试daemon启动
echo "3. 测试后台服务启动..."
./build/ai_glass_test --daemon
sleep 3

# 4. 检查状态
echo "4. 检查服务状态..."
./build/ai_glass_cmd --status

if [ $? -eq 0 ]; then
    echo ""
    echo "🎉 后台服务启动成功！"
    echo ""
    echo "演示并发使用:"
    echo "==================="
    
    # 演示Linux命令正常工作
    echo "Linux命令 'ls':"
    ls
    echo ""
    echo "Linux命令 'date':"
    date  
    echo ""
    
    # 演示AI Glass命令正常工作
    echo "AI Glass命令 'AT+AIGLASSPHOTO':"
    ./build/ai_glass_cmd "AT+AIGLASSPHOTO"
    echo ""
    echo "AI Glass命令 'AT+STATUS':"
    ./build/ai_glass_cmd "AT+STATUS"
    echo ""
    
    # 停止服务
    echo "停止后台服务..."
    ./build/ai_glass_cmd "AT+EXIT"
    
    echo ""
    echo "✅ 测试完成！新架构工作正常。"
    echo ""
    echo "使用说明:"
    echo "  启动: ./build/ai_glass_test --daemon"
    echo "  命令: ./build/ai_glass_cmd \"AT+命令\""
    echo "  状态: ./build/ai_glass_cmd --status"
    echo "  停止: ./build/ai_glass_cmd \"AT+EXIT\""
else
    echo ""
    echo "❌ 后台服务启动失败"
    echo ""
    echo "调试信息:"
    echo "==========="
    echo "进程状态:"
    ps aux | grep ai_glass || echo "没有找到ai_glass进程"
    echo ""
    echo "日志文件:"
    if [ -f "/tmp/ai_glass_daemon.log" ]; then
        echo "--- /tmp/ai_glass_daemon.log ---"
        cat /tmp/ai_glass_daemon.log
    else
        echo "日志文件不存在"
    fi
    echo ""
    echo "管道文件:"
    ls -la /tmp/ai_glass_* 2>/dev/null || echo "管道文件不存在"
    exit 1
fi